/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.orderView;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TOrder;
import com.ruipengkj.bean.TUser;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.MatcherFormatUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.display.ClientDisplay;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.service.TOrderService;
import com.ruipengkj.service.TUserService;
import com.ruipengkj.view.orderView.dish.PayJPopupMenu;

/**
 * 说明：
 * 确认支付Dialog
 * @Author：李智深
 * @Date：2012-03-20
 */
public class MemberConsumptionConfirmPaymentDailog extends IDialog implements CaretListener{

	private static final long serialVersionUID = 1L;

	private JLabelJTextFieldComponent totalMoneyTF=null;//总金额
	private JLabelJTextFieldComponent receivableMoneyTF=null;//应收金额
	private JLabelJTextFieldComponent discountTF=null;//折扣
	private JLabelJTextFieldComponent privilegeTF=null;//优惠
	private JLabelJTextFieldComponent menberLevelTF=null;//会员级别
	private JLabelJComboBoxComponent payModeBox=null;//支付方式
	private JLabelJTextFieldComponent receiptTF=null;//收款
	private JLabelJTextFieldComponent needMoney;//仍需支付金额 会员卡支付
	private JLabelJTextFieldComponent returnMoney;//应找金额
	private JLabelJTextFieldComponent userMoney;//会员卡余额
	
	private JButton playButton;//付款;
	private JButton celButtonl;//取消
	
	private TOrderService tOrderService;//订单
	private TUserService tUserService;//用户
	private TUser tUser;//会员
	private TOrder tOrder;//订单
	public boolean isSuccess=false;
	
//	private int type;//1、新订单 2、已有订单，直接付款
	private double money = 0;
	private JPanel main_jp;
	private TOrder order=new TOrder();
	public MemberConsumptionConfirmPaymentDailog(JDialog jd, String title,boolean b) {
		super(jd, title, b);
		this.init();
		this.setSize(350, 536);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
	}
	
	private void init(){
		tUserService=BuildSpringApplication.getInstance().getTUserServiceImpl();
		tOrderService=BuildSpringApplication.getInstance().getTOrderServiceImpl();
		this.initViews();
		this.initListener();
	}
	
	private void initViews(){
		main_jp = new BorderJPanel();
		main_jp.setBackground(Color.white);
		BoxLayout boxLayout=new BoxLayout(main_jp,BoxLayout.Y_AXIS);
		main_jp.setLayout(boxLayout);
		
		userMoney = new JLabelJTextFieldComponent("卡 余 额：", 33, 33);
		menberLevelTF=new JLabelJTextFieldComponent("会员级别：", 33, 33);
		payModeBox=new JLabelJComboBoxComponent("支付方式：",ApplicationContext.PLAY_MATHOD_MAP(),200, 33);
		discountTF=new JLabelJTextFieldComponent("会员折扣：", 33, 33);
		privilegeTF=new JLabelJTextFieldComponent("优惠金额：", 33, 33);
		totalMoneyTF=new JLabelJTextFieldComponent("总 金 额：", 33, 33);
		receivableMoneyTF=new JLabelJTextFieldComponent("应收金额：", 33, 33);
		receivableMoneyTF.getText().setForeground(Color.RED);
		receiptTF=new JLabelJTextFieldComponent("收    款：", 33, 33);
		needMoney = new JLabelJTextFieldComponent("仍需金额：", 33, 33);
		needMoney.getText().setForeground(Color.RED);
		returnMoney = new JLabelJTextFieldComponent("应找金额：", 33, 33);
		
		needMoney.getText().setText("0.00");		
		menberLevelTF.getText().setText("无");//会员级别
		discountTF.getText().setText("无");//会员折扣
		privilegeTF.getText().setText("0.00");//优惠金额
		totalMoneyTF.getText().setText("0.00");//总 金 额
		receivableMoneyTF.getText().setText("0.00");//应收金额
		
		userMoney.getText().setText("非会员");
		needMoney.getText().setEditable(false);
		menberLevelTF.getText().setEditable(false);
		discountTF.getText().setEditable(false);
		privilegeTF.getText().setEditable(false);
		totalMoneyTF.getText().setEditable(false);
		receivableMoneyTF.getText().setEditable(false);
		returnMoney.getText().setEditable(false);
		userMoney.getText().setEditable(false);
		
		JPanel jp1=new JPanel();
		playButton=new JButton("结  账");
		celButtonl=new JButton("取  消");
		
		Util.setSize(playButton, 100, 40);
		playButton.setFont(Util.FONT_20_PLAIN);
		
		Util.setSize(celButtonl, 100, 40);
		celButtonl.setFont(Util.FONT_20_PLAIN);
		
		jp1.add(playButton);
		jp1.add(celButtonl);
		
		main_jp.add(menberLevelTF);
		main_jp.add(payModeBox);
		main_jp.add(discountTF);
		main_jp.add(privilegeTF);
		main_jp.add(totalMoneyTF);
		main_jp.add(receivableMoneyTF);
		main_jp.add(userMoney, 6);
		main_jp.add(needMoney, 7);
		main_jp.add(receiptTF);
		main_jp.add(returnMoney);
		main_jp.add(jp1);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
		
		this.add(main_jp);
	}
	private void initListener(){
		payModeBox.getBox().addActionListener(this);
		playButton.addActionListener(this);
		celButtonl.addActionListener(this);
		receivableMoneyTF.getText().addKeyListener(this);
		receiptTF.getText().addKeyListener(this);
		receiptTF.getText().addCaretListener(this);
		receiptTF.getText().addMouseListener(this);
		this.addWindowListener(new WindowAdapter(){ 
			public void windowActivated(WindowEvent e){ 
				receiptTF.getText().requestFocus();
			}
		});
	}
	public void showDialog(TUser tUser,double TotalManay,TOrder tOrder, String discount){
		this.tUser=tUser;
		this.isSuccess=false;
		this.order = tOrder;
		totalMoneyTF.getText().setText(TotalManay+"");
		receivableMoneyTF.getText().setText(TotalManay+"");//应收金额
		if(tUser!=null){
			payModeBox.getBox().setSelectedIndex(1);
			userMoney.getText().setText("");
			userMoney.getText().setText(tUser.getMoney()+"");
			 
			if (tUser.getTShopMemberLevel()!=null) {
//				double receivable=TotalManay*tUser.getTShopMemberLevel().getDiscount();
//				receivableMoneyTF.getText().setText(receivable+"");//应收金额
//				discountTF.getText().setText(tUser.getTShopMemberLevel().getDiscount()+"");//折扣
//				privilegeTF.getText().setText(TotalManay-receivable+"");//优惠
				menberLevelTF.getText().setText(tUser.getTShopMemberLevel().getName());//会员级别
			}
		}
		double receivable = TotalManay*Double.parseDouble(discount);
//		needMoney.getText().setText(receivable+"");
		if (tUser == null) {
			needMoney.getText().setText(receivableMoneyTF.getText().getText());
		} else {
			double money = receivable-tUser.getMoney();
			needMoney.getText().setText(money >= 0 ? money+"" : "0.0");
		}
		receivableMoneyTF.getText().setText(receivable+"");//应收金额
		discountTF.getText().setText(discount);//折扣
		privilegeTF.getText().setText(TotalManay-receivable+"");//优惠
		try {
			//输出客显  应付金额
			ClientDisplay.sendDisplay(ClientDisplay.DISPLAY_STATE_AMOUNT,receivableMoneyTF.getText().getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.setVisible(true);
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==playButton){
			//确定
			String play=payModeBox.getBox().getSelectedItem().toString();
			if(play.equals(ApplicationContext.PLAY_MATHOD_TEXT7)){
				receiptTF.getText().setEditable(true);
				String maney=receiptTF.getText().getText().trim();
				String totalmaney= totalMoneyTF.getText().getText().trim();
				if(!MatcherFormatUtil.MatcherPriceScheme(maney)){
					JOptionPane.showMessageDialog(null, "收款金额 不能为空，且小数点左边最多10位数字，右边最多2位数字");
					receiptTF.getText().setText("");
					receiptTF.requestFocus();
					return;
				}
				if(Double.parseDouble(maney)<Double.parseDouble(receivableMoneyTF.getText().getText().trim())){
					JOptionPane.showMessageDialog(null, "收款金额不能小于仍需金额");
					receiptTF.requestFocus();
					return;
				}
				if(!MatcherFormatUtil.MatcherPriceScheme(totalmaney)){
					JOptionPane.showMessageDialog(null, "总金额 不能为空，且小数点左边最多10位数字，右边最多2位数字");
					totalMoneyTF.getText().setText("");
					totalMoneyTF.requestFocus();
					return;
				}
				try {
					tOrder=getTOrder();
					
					tOrder.setTComment(null);
					tOrderService.saveOrUpdateService(tOrder);
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "下单失败");
					this.isSuccess=false;
				}
				this.isSuccess=true;
				double zhao=(Double.parseDouble(maney)-Double.parseDouble(receivableMoneyTF.getText().getText().trim()));
				ApplicationContext.CHANGE_MANEY=zhao;//找零
				ApplicationContext.CHANGE_CASH=Double.parseDouble(receiptTF.getText().getText()+"");//现金
				//输出客显  找零金额
				try {
					ClientDisplay.sendDisplay(ClientDisplay.DISPLAY_STATE_CHAGNE,zhao+"");
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				JOptionPane.showMessageDialog(null, "找零："+zhao);
				
			} else {
				String maney=receiptTF.getText().getText().trim();
				String totalmaney= totalMoneyTF.getText().getText().trim();
				if (money > 0) {
					if(!MatcherFormatUtil.MatcherPriceScheme(maney)){
						JOptionPane.showMessageDialog(null, "卡余额不足，因此收款金额 不能为空，且小数点左边最多10位数字，右边最多2位数字");
						receiptTF.getText().setText("");
						receiptTF.requestFocus();
						return;
					}
					if(Double.parseDouble(maney)<Double.parseDouble(needMoney.getText().getText().trim())){
						JOptionPane.showMessageDialog(null, "收款金额不能小于仍需金额");
						receiptTF.requestFocus();
						return;
					}
					if(!MatcherFormatUtil.MatcherPriceScheme(totalmaney)){
						JOptionPane.showMessageDialog(null, "总金额 不能为空，且小数点左边最多10位数字，右边最多2位数字");
						totalMoneyTF.getText().setText("");
						totalMoneyTF.requestFocus();
						return;
					}
				}
				try {
					tOrder=getTOrder();
					tOrderService.saveOrUpdateService(tOrder);
					this.isSuccess=true;
					if (money > 0) {
						order.setCachPayedAmount(tUser.getMoney());
						tUser.setMoney(0);
						double zhao=(Double.parseDouble(maney)-Double.parseDouble(needMoney.getText().getText().trim()));
						ApplicationContext.CHANGE_MANEY=zhao;
						JOptionPane.showMessageDialog(null, "找零："+zhao);
					} else {
						order.setCachPayedAmount(Double.parseDouble(receivableMoneyTF.getText().getText().trim()));
						tUser.setMoney(tUser.getMoney() - Double.parseDouble(receivableMoneyTF.getText().getText().trim()));
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "下单失败");
					this.isSuccess=false;
				}
			}
			
			if(tUser!=null){
				try {
					tUser.setTotalBuyMoney(tUser.getTotalBuyMoney()+Double.parseDouble(receivableMoneyTF.getText().getText().trim()));
					tUser.setBuyCount(tUser.getBuyCount()+1);
					tUserService.modifyService(tUser);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			this.dispose();
		}else if(e.getSource()==celButtonl){
			//取消
			if(Util.showConfirmDialog("是否取消支付？")==0){
				this.dispose();
			}
		}else if(e.getSource()==payModeBox.getBox()){
			//选择付款方式
			String play=payModeBox.getBox().getSelectedItem().toString();
			if(play.equals(ApplicationContext.PLAY_MATHOD_TEXT7)){
				needMoney.getText().setText("0.00");
				if (tUser == null || tUser.getTShopMemberLevel() == null) {
					receivableMoneyTF.getText().setText(totalMoneyTF.getText().getText());//应收金额
				} else {
					double receivable=(Double.parseDouble(totalMoneyTF.getText().getText()))*tUser.getTShopMemberLevel().getDiscount();
					receivableMoneyTF.getText().setText(receivable+"");//应收金额
				}
//				if (tUser == null) {
					needMoney.getText().setText(receivableMoneyTF.getText().getText());
//				} else {
//					double money = Double.parseDouble(receivableMoneyTF.getText().getText())-tUser.getMoney();
//					needMoney.getText().setText(money >= 0 ? money+"" : "0.0");
//				}
//				main_jp.remove(userMoney);
//				main_jp.remove(needMoney);
//				main_jp.updateUI();
				receiptTF.getText().setEditable(true);
			}else{
				if (tUser == null || tUser.getCardNum().equals("")) {
					JOptionPane.showMessageDialog(null, "非会员，不允许会员卡消费");
					payModeBox.getBox().setSelectedIndex(0);
					return;
				} else {
					main_jp.add(userMoney, 6);
					main_jp.add(needMoney, 7);
					money = Double.parseDouble(receivableMoneyTF.getText().getText().trim()) - tUser.getMoney();
					if (money > 0) {
						needMoney.getText().setText(String.valueOf(money));
//						JOptionPane.showMessageDialog(null, "会员卡余额不足，仍需支付金额："+money+"元");
						return;
					}
				}
				
				needMoney.getText().setText("0.0");
				receiptTF.getText().setEditable(false);
			}
			zhao();
		} else {
			super.actionPerformed(e);
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getSource()==receivableMoneyTF.getText()){
			//查询会员
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				playButton.doClick();
			}
		}else if(e.getSource()==receiptTF.getText()){
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
					playButton.doClick();
			}
		}
	}
	private TOrder getTOrder(){
		order.setWorkShiftID(ApplicationContext.WORKSHIFT_ID);
		//支付方式
		order.setPayWay((Byte)payModeBox.getKeyByVaule(payModeBox.getBox().getSelectedItem().toString()));
		order.setStatus(ApplicationContext.ORDER_STATUS07);//TINYINT定单状态1为开始创建的定单 2为确认定单 3为已确定支付方式 4为定单已分配（确认货源） 5为定单正在执行调度 6为定单已发货 7为定单已完成 该字节的10位为撤消标记 0为没有撤消，1为正在撤消
		order.setPayStatus(ApplicationContext.PLAY_STATUS_YES);//支付状态 1为未支付 2为已支付 
		order.setSendWay(ApplicationContext.ORDER_SENDWAY_MODT1);//配送方式  1为送货上门 2为物流
		order.setEndWay(ApplicationContext.ORDER_ENDWAY_MODT1);//结束方式0为未设置 1为成功完成 2为已合并 3为已取消 4为卖家已取消 5为卖家无法送抵（比如说买家不要了）
		order.setTotalAmount(Double.parseDouble(totalMoneyTF.getText().getText().trim()));//总金额DECIMAL(20,3)
		order.setNeedMoney(Double.parseDouble(receivableMoneyTF.getText().getText().trim()));//应支付金额
		order.setPayedAmount(Double.parseDouble(receivableMoneyTF.getText().getText().trim()));//已支付金额
		order.setDiscountAmount(Double.parseDouble(totalMoneyTF.getText().getText().trim())-Double.parseDouble(receivableMoneyTF.getText().getText().trim()));//优惠金额
//		if (tUser == null || tUser.getTShopMemberLevel() == null) {
//			order.setDiscountAmount(0);
//		} else {
//			order.setDiscountAmount(Double.parseDouble(totalMoneyTF.getText().getText())*tUser.getTShopMemberLevel().getDiscount());
//		}
		
		order.setPayID("");//支付单编号 CHAR(15)
		order.setOrderType(ApplicationContext.ORDERTYPE1);//定单类型 TINYINT 1为个人定单 21为企业定单（个人支付） 22为企业定单（企业支付） 3为楼宇定餐定单，当类型为3时，群组编号为定单生成时的位置编号
		order.setCommentStatus(ApplicationContext.COMMENNTSTATUS1);//评价状态 十位为1商店是否已评价，0为未评价 个位为1商品是否已评价，0为未评价
		order.setCancelReason("");//取消原因 VARCHAR(256)
		order.setNote("");//定单备注 VARCHAR(512)
		order.setSource(ApplicationContext.ORDER_SOURCE1);//订单来源CHAR(15)
		order.setType(ApplicationContext.ORDER_TYPE1+"");//订单类型CHAR(18)1为零售 2为批发
		order.setSaler(ApplicationContext.OPERATOR_ID);//销售人CHAR(15)
		order.setOperator(ApplicationContext.OPERATOR_ID);//操作人CHAR(15)
		order.setBillType(ApplicationContext.BILLTYPE1);//票据类型TINYINT 1为收据  2为发票
		order.setInvoice("");//发票号VARCHAR(30)
		order.setCardPayedAmount(0);//会员卡支持金额DECIMAL(20,3)
		order.setTUser(tUser);
//		order.setSendInfo(null);//配送地址编号CHAR(15)
		return order;
	}

	public TOrder gettOrder() {
		return tOrder;
	}

	public void settOrder(TOrder tOrder) {
		this.tOrder = tOrder;
	}

	private void zhao() {
		String play=payModeBox.getBox().getSelectedItem().toString();
		String maney=receiptTF.getText().getText().trim();
		if (maney == null || maney.equals(""))
			maney = "0";
		double zhao = 0;
		if(play.equals(ApplicationContext.PLAY_MATHOD_TEXT7)){
			if (receivableMoneyTF.getText().getText().trim().equals("")) 
				receivableMoneyTF.getText().setText("0.0");
			zhao=(Double.parseDouble(maney)-Double.parseDouble(receivableMoneyTF.getText().getText().trim()));
		} else {
			zhao=(Double.parseDouble(maney)-Double.parseDouble(needMoney.getText().getText().trim()));
		}
		returnMoney.getText().setText(zhao+"");
	}
	@Override
	public void caretUpdate(CaretEvent e) {
		if (e.getSource() == receiptTF.getText()) {
			zhao();
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == receiptTF.getText()) {
			new PayJPopupMenu(receiptTF.getText()).show(receiptTF, receiptTF.getWidth(), 0);
		}
	}
}
